<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//引用对应的命名空间
use Gregwar\Captcha\CaptchaBuilder;
use Session;

class LoginController extends Controller {

    public function login(Request $request) {//登录页面  
        return view("log.login");
    }

    public function log(request $request) {//处理登陆 
        //获取数据
        $str = $_POST['str'];
        //将表单序列化的值转换成数组
        parse_str($str, $arr);
        $userInput =$arr["code"];
        //验证码验证 
        if (Session::get('milkcaptcha') ==$userInput) {
            //用户输入验证码正确 
        } else {
            //用户输入验证码错误
           echo 2;
           exit();
        }
        $rule = [
            'name' => 'required|between:6,12',
            'pass' => 'required|between:6,12', 
        ];
        $message = [
            'name.required' => "请输入用户名", 
            'name.between' => "用户名长度应在6-12个字符之间",
            'pass.required' => "请输入密码", 
            'pass.between' => "密码长度应在6-12个字符之间", 
        ];
        $validator = \Validator::make($arr, $rule, $message);
        if ($validator->passes()) { 
            $data=\DB::table("admin")->where(["name"=>$arr["name"],"pass"=>$arr["pass"],"status"=>0])->first();
            if($data){
               session(['user' => $arr["name"]]);
               echo 1; //验证成功跳转到首页  
            }else{
               echo 3;
            }  
        } else {
            return $validator->getMessageBag()->getMessages();
        }
        
    }

    public function code($tmp) {//获取验证码    
        $builder = new CaptchaBuilder;//生成验证码图片的Builder对象，配置相应属性 
        $builder->build($width = 100, $height = 40, $font = null);//可以设置图片宽高及字体 
        $phrase = $builder->getPhrase();//获取验证码的内容 
        Session::flash('milkcaptcha', $phrase);//把内容存入session 
        header("Cache-Control: no-cache, must-revalidate"); //清除缓存
        header('Content-Type: image/jpeg');
        $builder->output();//生成图片
    } 
}
